package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.RoleBean;
import com.project.mapper.IPermissionMapper;
import com.project.mapper.IRoleMapper;
import com.project.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IPermissionMapper permissionMapper;

    //动态分页查询角色集合
    @Override
    public IPage<RoleBean> findByItem(Integer pageNO) {
        return roleMapper.selectPage(new Page<>(pageNO,3),null);
    }


    @Override
    public void del(Integer roleId) {
        roleMapper.del(roleId);

    }

    //添加角色，同时添加角色拥有的权限集合
    @Override
    public String add(RoleBean roleBean, Integer[] permission) {
        QueryWrapper qw=new QueryWrapper<>();
        qw.eq("r_name",roleBean.getName());
        if (roleMapper.selectOne(qw)==null) {
            roleMapper.insert(roleBean);
            permissionMapper.addPermissionByRoleId(roleBean.getId(), permission);
            return "ok";
        }
        return "";
    }

    //通过角色id修改用户权限，先删除该角色的所有权限，在添加新的权限
    @Override
    public void update(Integer roleId, Integer[] newArray) {
        //删除该角色的所有权限
        roleMapper.delPermissionByRoleId(roleId);
        //添加新权限
        permissionMapper.addPermissionByRoleId(roleId,newArray);

    }

    @Override
    public List<RoleBean> findAll() {
        return roleMapper.selectList(null);
    }

    @Override
    public RoleBean findById(Integer roleId) {
        return roleMapper.findById(roleId);
    }

}
